package com.junxonline.plat.controller.base;

import com.junxonline.plat.dao.vo.PageResultVO;
import com.junxonline.plat.dao.vo.PageVO;
import com.junxonline.common.dao.vo.ResultVO;
import com.junxonline.common.exception.BizException;
import com.junxonline.common.exception.CommonBizException;
import com.junxonline.common.util.CommonUtils;
import com.junxonline.common.util.RedisUtils;
import com.junxonline.plat.exception.ErrorCodeEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author JunX
 * @ClassName: BaseController
 * @Description: Controller基类
 */

@Component
public class BaseController {

    protected Logger logger = LogManager.getLogger();

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取当前登录用户的Id
     * @return
     */
    protected Long getUserId() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        String token = request.getHeader("Authorization");

        String userId = (String) redisUtils.get("userId", "user-cache-" + token);

        try {
            if (CommonUtils.isEmpty(userId)) {
                response.sendRedirect("/401");
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw CommonBizException.SYSTEM_ERROR;
        }

        return Long.parseLong(userId);
    }

    /**
     * 带数据的公共返回方法
     *
     * @param returnObject 返回数据
     * @return
     */
    protected ResultVO getReturnSuccess(Object returnObject) {
        ResultVO result = new ResultVO();
        ErrorCodeEnum successEnum = ErrorCodeEnum.SUCCESS;
        result.setErrorCode(successEnum.getErrorCode());
        result.setErrorMsg(successEnum.getErrorMsg());
        result.setReturnData(returnObject);
        return result;
    }

    /**
     * 公共分页返回方法
     *
     * @param pageVO 返回数据
     * @return
     */
    protected PageResultVO getReturnSuccess(PageVO pageVO) {
        PageResultVO result = new PageResultVO();
        ErrorCodeEnum successEnum = ErrorCodeEnum.SUCCESS;
        result.setErrorCode(successEnum.getErrorCode());
        result.setErrorMsg(successEnum.getErrorMsg());
        result.setReturnData(pageVO.getData());
        result.setTotalCount(pageVO.getTotal());
        return result;
    }

    /**
     * 无数据的公共返回方法
     *
     * @return
     */
    protected ResultVO getReturnSuccess() {
        ResultVO result = new ResultVO();
        ErrorCodeEnum successEnum = ErrorCodeEnum.SUCCESS;
        result.setErrorCode(successEnum.getErrorCode());
        result.setErrorMsg(successEnum.getErrorMsg());
        return result;
    }

    /**
     * 错误的公共返回方法
     *
     * @param errorCodeEnum 错误枚举
     * @return
     */
    protected ResultVO getReturnError(ErrorCodeEnum errorCodeEnum) {
        ResultVO result = new ResultVO();
        result.setErrorCode(errorCodeEnum.getErrorCode());
        result.setErrorMsg(errorCodeEnum.getErrorMsg());
        return result;
    }

    /**
     * 将异常信息封装为Map返回
     *
     * @param errorCode
     * @param errorMsg
     * @param datas
     * @return
     */
    protected Map<String, Object> getReturnMap(Object errorCode, Object errorMsg, Object... datas) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("errorCode", errorCode);
        returnMap.put("errorMsg", errorMsg);
        if (datas != null && datas.length > 0) {
            returnMap.put("returnData", datas);
        }
        return returnMap;
    }

    /**
     * 当发生异常时执行
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    @ResponseBody
    public Map<String, Object> exception(Exception e) {
        if (e instanceof BizException) {
            BizException exception = (BizException) e;
            logger.info(exception.getMsg(), exception);
            return this.getReturnMap(exception.getCode(), exception.getMsg());
        } else {
            logger.info(ErrorCodeEnum.SYSTEM_ERROR.getErrorMsg(), e);
            return this.getReturnMap(ErrorCodeEnum.SYSTEM_ERROR.getErrorCode(), ErrorCodeEnum.SYSTEM_ERROR.getErrorMsg());
        }
    }

}
